package com.iwop.moto.controller;

import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.model.*;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.stringUtil.BankUtil;
import com.iwop.moto.utils.stringUtil.ObjectId;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import jxl.write.WriteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 //                            _ooOoo_
 //                           o8888888o
 //                           88" . "88
 //                           (| -_- |)
 //                            O\ = /O
 //                        ____/`---'\____
 //                      .   ' \\| |// `.
 //                       / \\||| : |||// \
 //                     / _||||| -:- |||||- \
 //                       | | \\\ - /// | |
 //                     | \_| ''\---/'' | |
 //                      \ .-\__ `-` ___/-. /
 //                   ___`. .' /--.--\ `. . __
 //                ."" '< `.___\_<|>_/___.' >'"".
 //               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 //                 \ \ `-. \_ __\ /__ _/ .-` / /
 //         ======`-.____`-.___\_____/___.-`____.-'======
 //                            `=---='
 //
 //         .............................................
 //                  佛祖保佑             永无BUG
 //          佛曰:
 //                  写字楼里写字间，写字间里程序员；
 //                  程序人员写程序，又拿程序换酒钱。
 //                  酒醒只在网上坐，酒醉还来网下眠；
 //                  酒醉酒醒日复日，网上网下年复年。
 //                  但愿老死电脑间，不愿鞠躬老板前；
 //                  奔驰宝马贵者趣，公交自行程序员。
 //                  别人笑我忒疯癫，我笑自己命太贱；
 //                  不见满街漂亮妹，哪个归得程序员？
 * @author czq
 * @version 1.0
 * @created 2016/9/30.
 */
@Controller
public class MWithdrawController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private SMSService sMSService;

    @Autowired
    private MWithdrawService mWithdrawService;

    @Autowired
    private MBankListService mBankListService;

    @Autowired
    private MPaymentService mPaymentService;

    @Autowired
    private MBankUtilService mBankUtilService;

    /**
     * @功能: 用户提现审核
     * @参数: userId 用户Id
     * @参数: realName 真实姓名
     * @参数: bankNo 银行卡号
     * @参数: code   验证码
     * @参数: drawingsMoney 提现金额
     * @参数: clientType 客户端类型(用户端：popular,维修端:1)
     */
    @RequestMapping("/api/user/drawings")
    @ResponseBody
    public ResultModel ApiUserDrawings() {
        SuperRecordModel srmParams = this.getSRModel();
        User user = userService.getUserBySid(srmParams.getString("userId"));
        try {
            if (user == null) {
                return getErr(ErrCode.USER_ERROR_NOEXIST);
            }
            String drawingsMoney = srmParams.getString("drawingsMoney");
            Double meney = Double.valueOf(drawingsMoney);
            if (user.getRmoney() < meney) {
                return getErr("输入的提现金额大于账户余额！");
            }
            String code = srmParams.getString("code");
            SMS sms = new SMS();
            sms.setTel(user.getUsername());
            sms.setContent(srmParams.getString("code"));
            sms = sMSService.findCheckCodeByTel(sms);
            if (sms == null) {
                return getErr(ErrCode.ERROR_SMS);
            } else if (sms.getStatus().equals("1")) {
                return getErr(ErrCode.ERROR_SMS_USED);
            } else if (false == sms.getContent().equals(code)) {
                return getErr(ErrCode.ERROR_SMS);
            }
            MBankList mBank = new MBankList();
            mBank.setSid(ObjectId.UUID());
            mBank.setUserId(user.getSid());
            mBank.setBankno(srmParams.getString("bankNo"));
            if (!BankUtil.checkBankCard(mBank.getBankno())) {
                return getErr("银行卡号不合法");
            }

        /*    MBankUtil mBankUtil = new MBankUtil();
            mBankUtil=mBankUtilService.getMBankUtilbycardbin(mBank.getBankno().substring(0,6));
            if (mBankUtil==null)
            {
                return getErr(ErrCode.ERROR_PARAME_KEY);
            }
            mBank.setBankSettleNo((mBankUtil.getBanksettleno().equals(null)) ? null : mBankUtil.getBanksettleno());
            mBank.setOrgName(mBankUtil.getOrgname().equals(null) ? null : mBankUtil.getOrgname());
*/
            mBank.setBankType(BankUtil.getNameOfBank(mBank.getBankno()));
            mBank.setRealName(srmParams.getString("realName"));
            mBank.setAddTime(new Date());
            mBank.setStatusFlag("0");
            mBank.setStatusTime(new Date());
            mBank.setBankBranch(srmParams.getString("bank_branch"));
            mBankListService.insertMBankList(mBank);
            MWithdraw mWithdraw = new MWithdraw();
            mWithdraw.setSid(ObjectId.UUID());
            mWithdraw.setBankId(mBank.getSid());
            mWithdraw.setUserId(mBank.getUserId());
            mWithdraw.setRmoney(meney);
            mWithdraw.setAddTime(new Date());
            mWithdraw.setAuditStatus("0");
            user.setRmoney(user.getRmoney() - meney);//体现扣款
            mWithdraw.setOrderNo(SequenceUtil.Serial("S"));
            mWithdraw.setClientType(srmParams.getString("clientType"));
            mWithdrawService.insertWMithdrawService(mWithdraw);
            userService.updateUserRmoneyBySid(user);
            sms.setStatus("1");
            sMSService.save(sms);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * @参数: auditStatus 审核状态:Drawings 待提现审核单
     */
    @RequestMapping("/api/drawings/audit/list")
    @ResponseBody
    public ResultModel ApiDrawingsAuditList() {
        SuperRecordModel srmParams = this.getSRModel();
        try {
            List<SuperRecordModel> list = mWithdrawService.findWithdrawByStatus(srmParams);
            return getSucceed(list);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    /**
     * @功能: 财务提现审核
     * @日期: liuwb by 2016-11-13 09:31 create
     * @参数: sid 审核表主键
     * @参数: auditStatus 审核状态 [Drawings:审核中] [Pass:通过] [Refuse:拒绝][alreadyPay:已打款]
     * @参数: check_user_id 审核Id
     * @参数: check_user_realname 审核人姓名
     */
    @RequestMapping("Api/withdraw/audit")
    @ResponseBody
    @Transactional
    public ResultModel ApiWithdrawAudit() {
        SuperRecordModel srmParams = this.getSRModel();
        String sid = String.valueOf(srmParams.get("sid"));
        try {
            MWithdraw mw = mWithdrawService.getMWithdrawServiceBySid(sid);
//            if (!mw.getAuditStatus().equals("0")) {
//                return getErr(ErrCode.ERROR_AUDIT_WITHDRAW);
//            }
            if (srmParams.get("auditStatus").equals("1")) {
                srmParams.put("auditStatus", "1");
                mWithdrawService.updateWithdrawAuditStatus(srmParams);
                return getSucceed(ErrCode.SUCCEED);
            } else if (srmParams.get("auditStatus").equals("3")) {
                srmParams.put("auditStatus", "3");
                mWithdrawService.updateWithdrawAuditStatus(srmParams);
                return getSucceed(ErrCode.SUCCEED);
            } else if (srmParams.get("auditStatus").equals("2")) {
                if (mw.getAuditStatus().equals("2")) {
                    return getSucceed(ErrCode.ERROR_REFUCE);
                }
                srmParams.put("auditStatus", "2");
                //明细已扣金额
                Double rmoney = mw.getRmoney();
                User user = userService.getUserBySid(mw.getUserId());
                //拒绝资金打回
                user.setRmoney(user.getRmoney() + rmoney);
                userService.updateUserRmoneyBySid(user);
                //update拒绝状态
                mWithdrawService.updateWithdrawAuditStatus(srmParams);

                //插入一条回退记录
//                MPayment mPayment = new MPayment();
//                mPayment.setPayId(ObjectId.UUID());
//                mPayment.setPayType("Backspace");
//                mPayment.setPayTime(new Date());
//                mPayment.setPayMoney(rmoney);
//                mPayment.setPayStatus("1");
//                mPayment.setSellerUserId(mw.getUserId());
//                mPayment.setBuyerUserId(mw.getUserId());
//                mPayment.setPayDescribe("用户提现审核失败，回退金额");
//                mPayment.setOutTradeNo(SequenceUtil.Serial("S"));
//                mPaymentService.insert(mPayment);
                return getErr(ErrCode.SUCCEED);
            } else {
                mWithdrawService.updateWithdrawAuditStatus(srmParams);
                return getErr(ErrCode.SUCCEED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLog(e, "Api/withdraw/audit");
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    @RequestMapping("/api/mwidraw/add")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel mwindrawAdd(@ModelAttribute MWithdraw mWithdraw, HttpServletRequest request) {
        mWithdraw.setSid(UUID.randomUUID().toString());
        mWithdraw.setAuditStatus("0");
        mWithdraw.setAddTime(new Date());
        mWithdraw.setRmoney(mWithdraw.getRmoney() * 100);
        mWithdraw.setOrderNo(SequenceUtil.Serial("S"));
        mWithdraw.setUserId(request.getParameter("session_id"));
        try {
            mWithdrawService.insertWMithdrawService(mWithdraw);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    @RequestMapping("/api/mwidraw/edit")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel mwindrawEdit(@ModelAttribute MWithdraw mWithdraw, HttpServletRequest request) {
        try {
            MWithdraw mw = mWithdrawService.getMWithdrawServiceBySid(mWithdraw.getSid());
            if (mw == null) {
                return getErr(ErrCode.ERROR_SYSTEM);
            }
            mWithdraw.setCheckUserId(request.getParameter("session_id"));
            mWithdraw.setCheckTime(new Date());
            mWithdrawService.editWMithdrawService(mWithdraw);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    @RequestMapping("/api/mwidraw/detail")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel mwindrawDetail(HttpServletRequest request) {
        try {
            MWithdraw mw = mWithdrawService.getMWithdrawServiceBySid(request.getParameter("sid"));
            return getSucceed(mw, ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    @RequestMapping("/api/mwidraw/list")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel mwindrawList(HttpServletRequest request) {
        try {
            SuperRecordModel srm = this.getSRModel();
            List<MWithdraw> mw = mWithdrawService.getMWithdrawServiceList(srm);
            return getSucceed(mw, ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 导出审核通过记录
     * Created by dpngmq on 2017/03/20.
     * @参数: clientType 是商家还是客户
     * @参数: auditStatus 审核状态 [Drawings:0] [1:通过] [2:拒绝][3:已打款]
     * @参数: check_user_id 审核Id
     * @参数: check_user_realname 审核人姓名
     */
    @RequestMapping("/api/user/drawings/export")
    @ResponseBody
    public ResultModel Withdrawexport( HttpServletResponse response) throws IOException, WriteException {

        try {
            SuperRecordModel srmParams = this.getSRModel();

            //确认是审核通过
            if (srmParams.get("auditStatus").equals("1")) {

            }else
            {
                return getErr(ErrCode.ERROR_PARAMETER);
            }
            if (srmParams.get("clientType").equals("1")||srmParams.get("clientType").equals("popular")) {

            }else
            {
                return getErr(ErrCode.ERROR_PARAMETER);
            }

            List<SuperRecordModel> models = mWithdrawService.findWithdrawexport(srmParams);

            String title[] = {"收款方户名", "收款方账号", "金额", "备注", "联行号"};
            String fileName = new String();
            String filesheetname = new String();

            List<List> lists = new ArrayList<List>();

            for (SuperRecordModel po : models) {

                List<Object> cusList = new ArrayList<>();

                String  banksettlenoorgname = new String();
                cusList.add(po.getString("real_name"));
                cusList.add(po.getString("bankno"));
                cusList.add(po.get("drawings_money"));
                cusList.add(po.getString("realname"));

                if(po.getString("bank_settle_no").toString().equals(null)||po.getString("bank_settle_no").isEmpty()||po.getString("bank_settle_no")==null)
                {
                    banksettlenoorgname = "305100000013"+"-";
                }else
                {
                    banksettlenoorgname = po.getString("bank_settle_no")+"-";
                }

                if(po.getString("org_name").toString().equals(null)||po.getString("org_name").isEmpty()||po.getString("org_name")==null)
                {
                    banksettlenoorgname =banksettlenoorgname+"摩邦车联网";
                }else
                {
                    banksettlenoorgname = banksettlenoorgname+po.getString("org_name");
                }
                cusList.add(banksettlenoorgname);
                lists.add(cusList);
            }
            response.reset();
            response.setContentType("octets/stream");
            if(srmParams.get("clientType").equals("1")) {
                fileName ="商店审核通过记录表.xls";
                filesheetname="商店审核通过列表";
            }else{
                fileName ="客户审核通过记录表.xls";
                filesheetname="客户审核通过列表";
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            OutputStream outputStream = response.getOutputStream();
            StringUtils.saveExcel(outputStream, title, lists,filesheetname );
            mWithdrawService.updatBatchexport(srmParams);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 审核通过记录批量打款
     * Created by dpngmq on 2017/03/29.
     * @参数: clientType 是商家还是客户
     * @参数: auditStatus 审核状态 [0:审核中] [1:通过] [2:拒绝][3:已打款]
     * @参数: check_user_id 审核Id
     * @参数: check_user_realname 审核人姓名
     */
    @RequestMapping("/api/user/drawings/payment")
    @ResponseBody
    public ResultModel WithdrawBatchPayment( HttpServletResponse response) throws IOException, WriteException {
        try {
            SuperRecordModel srmParams = this.getSRModel();
            mWithdrawService.updatBatchAuditStatus(srmParams);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


}

